package pers.ree.demo.concurrent;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ForkJoinPoolDemo {
    public static void main(String[] args) {
//        int[] array = new int[1000];
//        for (int i = 0; i < array.length; i++) {
//            array[i] = i + 1;
//        }
//
//        ForkJoinPool forkJoinPool = new ForkJoinPool();
//        Integer sum = forkJoinPool.invoke(new SumTask(array, 0, array.length));
//        System.out.println("Sum: " + sum);

        int[] array = new int[1000];
        for (int i = 0; i < array.length; i++) {
            array[i] = i + 1;
        }

        // 初始化数组
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        // 使用 invoke
        Integer sumInvoke = forkJoinPool.invoke(new SumTask(array, 0, array.length));
        System.out.println("Sum using invoke: " + sumInvoke);
        // 使用 join
        SumTask sumTaskJoin = new SumTask(array, 0, array.length);
        forkJoinPool.execute(sumTaskJoin);
        Integer sumJoin = sumTaskJoin.join();
        System.out.println("Sum using join: " + sumJoin);
    }
}

class SumTask extends RecursiveTask<Integer> {
    private final int[] array;
    private final int start;
    private final int end;

    public SumTask(int[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if (end - start <= 10) {
            // 当子任务处理的数组长度较小时，直接计算
            int sum = 0;
            for (int i = start; i < end; i++) {
                sum += array[i];
            }
            return sum;
        } else {
            // 将任务分成两个子任务
            int mid = (start + end) / 2;
            SumTask leftTask = new SumTask(array, start, mid);
            SumTask rightTask = new SumTask(array, mid, end);
            leftTask.fork();
            rightTask.fork();
            return leftTask.join() + rightTask.join();
        }
    }
}
